package com.chy.blog_web.modular.web.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.blog_web.core.util.UploadURLUtil;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.mapper.BoArticleMapper;
import com.chy.blog_web.modular.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 描述：文章表 service业务层
 * 作者：chenhuiyan
 * 时间：2020/03/01 12:03
 */
@Service
@Transactional(readOnly = true)
public class BoArticleServiceImpl extends ServiceImpl<BoArticleMapper, BoArticle> implements IBoArticleService {

    @Autowired
    private IBoPraiseHistoryService boPraiseHistoryService;

    @Autowired
    private IBoCommentService boCommentService;

    @Autowired
    private IBoImgLogService boImgLogService;

    @Autowired
    private IBoArticleTagService boArticleTagService;

    /**
     * 查询列表
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> list(Map<String, Object> params){
        return baseMapper.list(params);
    }

    /**
     * 根据编号查询文章信息
     * @param articleId
     * @return
     */
    @Override
    public Map<String, Object> getArticleInfo(String articleId){
        return baseMapper.getArticleInfo(articleId);
    }

    /**
     * 查询列表总数
     * @param params
     * @return
     */
    @Override
    public int getCount(Map<String, Object> params){
        return baseMapper.getCount(params);
    }

    /**
     * 文章点赞
     * @param id
     * @param ipAddress 用户IP地址
     */
    @Override
    @Transactional(readOnly = false)
    public boolean updatePraiseNum(String id, String ipAddress){

        boolean flag = false;

        //先判断该IP今天是否点过赞
        Calendar calendar = Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR) + "";
        String month = (calendar.get(Calendar.MONTH) + 1) < 10? "0" + (calendar.get(Calendar.MONTH) + 1) : (calendar.get(Calendar.MONTH) + 1) + "";
        String day = calendar.get(Calendar.DATE) < 10? "0" + calendar.get(Calendar.DATE) : calendar.get(Calendar.DATE) + "";
        String date = year + "-" + month + "-" + day;
        BoPraiseHistory boPraiseHistory = boPraiseHistoryService.getOne(new QueryWrapper<BoPraiseHistory>()
                .eq("ip_address", ipAddress)
                .eq("service_id", id).like("time", date)
                .eq("type", 0));

        if(null == boPraiseHistory){
            BoArticle boArticle = baseMapper.selectById(id);
            boArticle.setPraiseNum(boArticle.getPraiseNum() + 1);

            //点赞记录
            boPraiseHistory = new BoPraiseHistory();
            boPraiseHistory.preInsert();
            boPraiseHistory.setServiceId(boArticle.getId());
            boPraiseHistory.setType(0);
            boPraiseHistory.setTime(new Date());
            boPraiseHistory.setIpAddress(ipAddress);

            baseMapper.updateById(boArticle); //更新文章点赞数量

            boPraiseHistoryService.save(boPraiseHistory); //保存点赞记录

            flag = true;
        }
        return flag;
    }

    /**
     * 评论点赞
     * @param id
     * @param ipAddress 用户IP地址
     */
    @Override
    @Transactional(readOnly = false)
    public boolean commPraise(String id, String ipAddress){

        boolean flag = false;

        //先判断该IP今天是否点过赞
        Calendar calendar = Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR) + "";
        String month = calendar.get(Calendar.MONTH) < 10? "0" + (calendar.get(Calendar.MONTH) + 1) : (calendar.get(Calendar.MONTH) + 1) + "";
        String day = calendar.get(Calendar.DATE) < 10? "0" + calendar.get(Calendar.DATE) : calendar.get(Calendar.DATE) + "";
        String date = year + "-" + month + "-" + day;
        BoPraiseHistory boPraiseHistory = boPraiseHistoryService.getOne(new QueryWrapper<BoPraiseHistory>()
                .eq("ip_address", ipAddress)
                .eq("service_id", id).like("time", date)
                .eq("type", 1));

        if(null == boPraiseHistory){
            BoComment boComment = boCommentService.getById(id);
            boComment.setPraise(boComment.getPraise() + 1);

            //点赞记录
            boPraiseHistory = new BoPraiseHistory();
            boPraiseHistory.preInsert();
            boPraiseHistory.setServiceId(boComment.getId());
            boPraiseHistory.setType(1);
            boPraiseHistory.setTime(new Date());
            boPraiseHistory.setIpAddress(ipAddress);

            boCommentService.updateById(boComment); //更新点赞数量

            boPraiseHistoryService.save(boPraiseHistory); //保存点赞记录

            flag = true;
        }
        return flag;
    }

    /**
     * 保存
     * @param boArticle
     * @param imgName 保存编辑器上传的图片名，用于记录相应的文章图片
     * @param imgSize 对应的图片大小
     * @param boTagArr 标签组
     * @return
     */
    @Transactional(readOnly = false)
    public Map<String, Object> saveData(BoArticle boArticle, String imgName, String imgSize, String boTagArr){
        Map<String, Object> res = new HashMap<>();

        //添加
        if(StrUtil.isEmpty(boArticle.getId())){
            boArticle.preInsert();

            if(boArticle.getUserName() == "" || boArticle.getUserName() == null){
                Random random = new Random();
                boArticle.setUserName("匿名游客_" + random.nextInt(99999));
            }

            boArticle.setType(1); //类型为游客发布
            boArticle.setIsPass(0); //审核中

            //保存图片记录
            if(!StrUtil.isEmpty(imgName)){
                String[] imgNameArr = imgName.split(","); //图片名
                Integer[] imgSizeArr = Convert.toIntArray(imgSize.split(",")); //图片大小
                List<BoImgLog> boImgLogList = new ArrayList<>();
                for(int index = 0; index < imgNameArr.length; index++){
                    BoImgLog boImgLog = new BoImgLog();
                    boImgLog.preInsert();
                    boImgLog.setImgName(imgNameArr[index]);
                    boImgLog.setImgSize(imgSizeArr[index]);
                    boImgLog.setTableName("bo_article");
                    boImgLog.setTableId(boArticle.getId());
                    boImgLog.setImgPath(UploadURLUtil.U_ARTICLE_IMAGE_PATH);
                    boImgLogList.add(boImgLog);
                }
                if(boImgLogList.size() > 0){
                    boImgLogService.saveBatch(boImgLogList);
                }
            }

            //保存标签
            List<BoArticleTag> boArticleTagList = new ArrayList<>();
            if(!StrUtil.isEmpty(boTagArr)){
                String[] tagArr = boTagArr.split(",");
                for(String tagStr: tagArr){
                    BoArticleTag boArticleTag = new BoArticleTag();
                    boArticleTag.preInsert();
                    boArticleTag.setArticleId(boArticle.getId());
                    boArticleTag.setTagId(tagStr);
                    boArticleTagList.add(boArticleTag);
                }
                if(boArticleTagList.size() > 0){
                    boArticleTagService.saveBatch(boArticleTagList);
                }
            }

            this.save(boArticle);
            res.put("state", "200");
            res.put("message", "发布成功，等待审核！");
        }
        return res;
    }

}
